var ProductGroupModule = function() {
  var editable = function() {
    return {
      init: function() {
        var oTable = $('#modelEditable').dataTable({
          //"autoWidth": false,
          "scrollX": true,
          "lengthMenu": [
            [10, 15, 20, 50],
            [10, 15, 20, 50]
          ],
          "displayLength": 10,
          "language": {
            "lengthMenu": "每页 _MENU_ 条记录",
            "paginate": {
              "previous": "上一页",
              "next": "下一页"
            },
            "info": "从 _START_ 到  _END_ 条，总记录为 _TOTAL_ 条",
            "infoEmpty": "记录数为0",
          },
          "columnDefs": [{
            "data": null,
            'sortable': false,
            "defaultContent": "<center>--</center>",
            "targets": [0]
          }, {
            "data": null,
            'sortable': false,
            "defaultContent": "<center>--</center>",
            "targets": [1]
          }, {
            "data": null,
            'sortable': false,
            "defaultContent": "<center>--</center>",
            "targets": [2]
          }],
          "columns": [{
            "data": "name"
          }, {
            "data": "number"
          }],
          "filter": false,
          "processing": false,
          "serverSide": true,
          "ajaxSource": ctx + "/productGroup/query",
          "serverMethod": "post",
          "fnRowCallback": function(nRow, aData, displayIndex) {
            nRow.children[0].id = aData.id;

            var opera = '<a class="detail fa fa-bars fa-lg" title="查看" href="javascript:;"></a>&nbsp;&nbsp;' +
              '<a class="edit fa fa-pencil-square-o fa-lg" title="修改" href="javascript:;"></a>&nbsp;&nbsp;' +
              '<a class="delete fa fa-times-circle-o fa-lg" title="删除" href="javascript:;"></a>';
            $('td:eq(2)', nRow).html(opera);
            return nRow;
          },
          "fnServerData": function(ajaxSource, dataSet, fnCallback) {
            var json = "";
            var s;
            for (var i = 0; i < dataSet.length; i++) {
              s = dataSet[i];
              if (s.name == 'sEcho') {
                json = json + '"echo":' + s.value;
              } else if (s.name == 'iDisplayStart') {
                json = json + ',"start":' + s.value;
              } else if (s.name == 'iDisplayLength') {
                json = json + ',"pageSize":' + s.value;
              }
            }
            var form = $("form#queryForm").serializeJSON();
            var js = form.replace('}', ',');
			json = js + json + "}";
            $.ajax({
              "contentType": "application/json; charset=UTF-8",
              "dataType": 'json',
              "type": "POST",
              "url": ajaxSource,
              "data": json,
              "success": fnCallback
            });
          },
        });
        $('#modelEditable').on("click", "a.detail", (function(e) {
          e.preventDefault();
          var nRow = $(this).parents('tr')[0];
          var id = nRow.children[0].id;
          window.location.href = "product/list?" + "productGroupId=" + id;
        }));
        $('#modelEditable').on("click", "a.edit", (function(e) {
          e.preventDefault();
          var nRow = $(this).parents('tr')[0];
          var id = nRow.children[0].id;
          $.ajax({
            type: "post",
            url: ctx + "/productGroup/edit/" + id,
            dataType: "json",
            success: function(msg) {
              if (msg.code == 1) {
                $("#editBody").empty(); // clean
                var tmpl = $("#editTemplate").tmpl(msg.data).appendTo("#editBody");
                var modal = $('#editModel').modal('show');
                modal.on("hidden.bs.modal", function(e) {
                  $(this).removeData();
                });

                var formEdit = $('#editForm');
                var validator = formEdit.validate({
                  rules: {
                    name: {
                      required: true,
                      rangelength: [1, 50],
                      remote: {
                        url: ctx + "/productGroup/check",
                        type: "post",
                        dataType: "json",
                        data: {
                          type: 1,
                          id: id
                        }
                      }
                    }
                  },
                  messages: {
                    name: {
                      remote: "组别名称已被使用！"
                    }
                  },
                  success: function(label, element) {
                    var icon = $(element).parent('.input-icon').children('i');
                    $(element).closest('.form-group').removeClass('has-error')
                      .addClass('has-success'); // set success class to the
                  },
                  submitHandler: function(form) {
                    var obj = $('form#editForm').serializeObject();
                    obj.id = id;
                    $('#editBtn').attr('disabled', true);
                    $.ajax({
                      type: "post",
                      url: ctx + "/productGroup/update",
                      data: obj,
                      success: function(msg) {
                        if (msg.code == 1) {
                          bootbox.dialog({
                            message: "修改组别成功！",
                            title: "温馨提示：",
                            buttons: {
                              main: {
                                label: "确定",
                                className: "btn btn-primary",
                                callback: function() {
                                  window.location.href = 'productGroup/list';
                                }
                              }
                            }
                          });
                          $('#editBtn').attr('disabled', false);
                        } else {
                          bootbox.dialog({
                            message: msg.message,
                            title: "温馨提示：",
                            buttons: {
                              main: {
                                label: "确定",
                                className: "btn btn-primary",
                                callback: function() {

                                }
                              }
                            }
                          });
                          $('#editBtn').attr('disabled', false);
                        }
                      },
                      error: function(msg) {
                        bootbox.alert("添加组别失败！");
                        $('#editBtn').attr('disabled', false);
                      }
                    });
                  }
                });
              } else {
                bootbox.alert(msg.message);
              }
            },
            error: function(msg) {
              bootbox.alert('Oh no,服务器出问题了！');
            }
          });
        }));
        $('#modelEditable').on("click", "a.delete", (function(e) {
          e.preventDefault();
          var nRow = $(this).parents('tr')[0];
          var id = nRow.children[0].id;
          var productGroupName = nRow.children[0].innerText;
          bootbox.dialog({
            title: "温馨提示：",
            message: "您确定要删除 " + productGroupName + "?",
            buttons: {
              danger: {
                label: "取 消",
                className: "btn btn-default",
                callback: function() {}
              },
              main: {
                label: "确 定",
                className: "btn btn-primary",
                callback: function() {
                  $.ajax({
                    type: "post",
                    url: ctx + "/productGroup/delete/"+id,
                    dataType: "json",
                    success: function(msg) {
                      if (msg.code == 1) {
                        bootbox.dialog({
                            message: "删除组别成功！",
                            title: "温馨提示：",
                            buttons: {
                              main: {
                                label: "确定",
                                className: "btn btn-primary",
                                callback: function() {
                                  window.location.href = 'productGroup/list';
                                }
                              }
                            }
                          });
                      } else {
                        bootbox.alert(msg.message);
                      }
                    },
                    error: function(msg) {
                      bootbox.alert('Oh,no!');
                    }
                  });
                }
              }
            }
          });
        }));

        $('#queryBtn').click(function() {
          oTable.fnClearTable();
        });
      }

    };

  }();

  return {
    init: function() {
      editable.init();
    }
  };
}();